from django.shortcuts import render, redirect
from .models import CustomUser
from main.models import Category
from django.contrib.auth.views import auth_login, auth_logout
from django.urls import reverse

# Create your views here.

def register(request):
    errors = None
    cs = Category.objects.all()
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        repassword = request.POST.get("repassword")
        if password != repassword:
            errors = "两次密码输入不一致"
        else:
            if CustomUser.objects.filter(username=username).exists():
                errors = "用户名已存在"
            else:
                user = CustomUser.objects.create_user(username=username, password=password)
                auth_login(request, user)
                return redirect(reverse("main:index"))
    return render(request, 'user/register.html', context={"cs": cs, "errors": errors})


def login(request):
    errors = None
    cs = Category.objects.all()
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = CustomUser.objects.filter(username=username).first()
        if user:
            if user.check_password(password):
                auth_login(request, user)
                next_url = request.GET.get("next")
                if next_url:
                    return redirect(to=next_url)
                else:
                    return redirect(reverse("main:index"))
            else:
                errors = "密码错误"
        else:
            errors = "用户名不存在"
    return render(request, 'user/login.html', context={"cs": cs, "errors": errors})


def logout(request):
    auth_logout(request)
    return redirect(reverse("main:index"))